<template>
  <div class="pending-posts">
    <div class="page-header">
      <h2>待审核帖子</h2>
      <el-button @click="fetchPosts" :loading="loading">
        <el-icon><Refresh /></el-icon>
        刷新
      </el-button>
    </div>

    <el-card>
      <el-table
        :data="posts"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />

        <el-table-column label="宠物信息" width="200">
          <template #default="{ row }">
            <div class="pet-info">
              <img
                v-if="row.pet.photo_url"
                :src="getFullImageUrl(row.pet.photo_url)"
                class="pet-photo"
                alt="宠物照片"
              />
              <div>
                <div class="pet-name">{{ row.pet.name || '未命名' }}</div>
                <div class="pet-details">
                  {{ row.pet.species }} · {{ row.pet.color }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="last_seen_location" label="最后目击地点" width="150" />

        <el-table-column label="目击时间" width="120">
          <template #default="{ row }">
            {{ formatDate(row.last_seen_time) }}
          </template>
        </el-table-column>

        <el-table-column label="发布者" width="120">
          <template #default="{ row }">
            {{ row.owner.username }}
          </template>
        </el-table-column>

        <el-table-column label="发布时间" width="120">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column label="线索数" width="80">
          <template #default="{ row }">
            <el-tag type="info">{{ row.sightings_count }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button size="small" @click="viewPost(row)" class="action-btn">
                查看详情
              </el-button>
              <el-button
                size="small"
                type="success"
                @click="approvePost(row)"
                :loading="operationLoading[row.id]?.approving"
                class="action-btn"
              >
                通过
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="rejectPost(row)"
                :loading="operationLoading[row.id]?.rejecting"
                class="action-btn"
              >
                拒绝
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 帖子详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="帖子详情"
      width="800px"
      :before-close="handleCloseDetail"
    >
      <div v-if="selectedPost" class="post-detail">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-section">
              <h4>宠物信息</h4>
              <div class="pet-detail">
                <img
                  v-if="selectedPost.pet.photo_url"
                  :src="getFullImageUrl(selectedPost.pet.photo_url)"
                  class="pet-detail-photo"
                  alt="宠物照片"
                />
                <div class="pet-detail-info">
                  <p><strong>名字：</strong>{{ selectedPost.pet.name || '未命名' }}</p>
                  <p><strong>品种：</strong>{{ selectedPost.pet.species }} - {{ selectedPost.pet.breed }}</p>
                  <p><strong>颜色：</strong>{{ selectedPost.pet.color }}</p>
                  <p><strong>性别：</strong>{{ selectedPost.pet.gender === 'male' ? '雄性' : '雌性' }}</p>
                  <p v-if="selectedPost.pet.description"><strong>描述：</strong>{{ selectedPost.pet.description }}</p>
                </div>
              </div>
            </div>
          </el-col>

          <el-col :span="12">
            <div class="detail-section">
              <h4>走失信息</h4>
              <p><strong>最后目击地点：</strong>{{ selectedPost.last_seen_location }}</p>
              <p><strong>最后目击时间：</strong>{{ formatDate(selectedPost.last_seen_time) }}</p>
              <p><strong>联系方式：</strong>{{ selectedPost.contact_info || '未提供' }}</p>
              <p><strong>发布者：</strong>{{ selectedPost.owner.username }}</p>
              <p><strong>发布时间：</strong>{{ formatDate(selectedPost.created_at) }}</p>
            </div>
          </el-col>
        </el-row>
      </div>

      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button
          type="success"
          @click="selectedPost && approvePost(selectedPost)"
          :loading="selectedPost && operationLoading[selectedPost.id]?.approving"
        >
          通过审核
        </el-button>
        <el-button
          type="danger"
          @click="selectedPost && rejectPost(selectedPost)"
          :loading="selectedPost && operationLoading[selectedPost.id]?.rejecting"
        >
          拒绝审核
        </el-button>
      </template>
    </el-dialog>

    <!-- 拒绝理由对话框 -->
    <el-dialog
      v-model="rejectDialogVisible"
      title="拒绝审核"
      width="400px"
    >
      <el-form :model="rejectForm" label-width="80px">
        <el-form-item label="拒绝理由">
          <el-input
            v-model="rejectForm.reason"
            type="textarea"
            :rows="4"
            placeholder="请输入拒绝理由（可选）"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="rejectDialogVisible = false">取消</el-button>
        <el-button
          type="danger"
          @click="confirmReject"
          :loading="rejecting"
        >
          确认拒绝
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, inject } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { getPendingPosts, reviewPost, type Post } from '@/api/posts'
import { getFullImageUrl } from '@/utils/helpers'
import dayjs from 'dayjs'

// 注入更新待审核数量的方法
const updatePendingCount = inject<(delta: number) => void>('updatePendingCount')

const posts = ref<Post[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 操作loading状态管理
const operationLoading = ref<Record<number, { approving?: boolean; rejecting?: boolean }>>({})

const detailDialogVisible = ref(false)
const selectedPost = ref<Post | null>(null)

const rejectDialogVisible = ref(false)
const rejecting = ref(false)
const rejectForm = reactive({
  reason: ''
})
let rejectPostData: Post | null = null

// 格式化日期
const formatDate = (date: string) => {
  return dayjs(date).format('MM-DD HH:mm')
}

// 获取待审核帖子列表
const fetchPosts = async () => {
  loading.value = true

  try {
    const response = await getPendingPosts({
      page: currentPage.value,
      limit: pageSize.value
    })

    posts.value = response.data
    total.value = response.pagination.totalItems

    // 初始化操作loading状态
    operationLoading.value = {}
    response.data.forEach(post => {
      operationLoading.value[post.id] = { approving: false, rejecting: false }
    })

  } catch (error) {
    console.error('获取待审核帖子失败:', error)
    ElMessage.error('获取待审核帖子失败')
  } finally {
    loading.value = false
  }
}

// 查看帖子详情
const viewPost = (post: Post) => {
  selectedPost.value = post
  detailDialogVisible.value = true
}

// 关闭详情对话框
const handleCloseDetail = () => {
  detailDialogVisible.value = false
  selectedPost.value = null
}

// 通过审核
const approvePost = async (post: Post) => {
  try {
    // 设置loading状态
    if (!operationLoading.value[post.id]) {
      operationLoading.value[post.id] = {}
    }
    operationLoading.value[post.id].approving = true

    await reviewPost(post.id, { admin_status: 'approved' })

    ElMessage.success('帖子审核通过')

    // 从列表中移除已审核的帖子
    const index = posts.value.findIndex(p => p.id === post.id)
    if (index > -1) {
      posts.value.splice(index, 1)
      total.value--

      // 更新Layout中的待审核数量徽章
      updatePendingCount?.(-1)
    }

    // 如果是在详情对话框中操作，关闭对话框
    if (detailDialogVisible.value) {
      detailDialogVisible.value = false
    }

  } catch (error) {
    console.error('审核失败:', error)
  } finally {
    if (operationLoading.value[post.id]) {
      operationLoading.value[post.id].approving = false
    }
  }
}

// 拒绝审核
const rejectPost = (post: Post) => {
  rejectPostData = post
  rejectForm.reason = ''
  rejectDialogVisible.value = true
}

// 确认拒绝
const confirmReject = async () => {
  if (!rejectPostData) return

  try {
    rejecting.value = true

    // 设置操作loading状态
    if (!operationLoading.value[rejectPostData.id]) {
      operationLoading.value[rejectPostData.id] = {}
    }
    operationLoading.value[rejectPostData.id].rejecting = true

    await reviewPost(rejectPostData.id, {
      admin_status: 'rejected',
      reason: rejectForm.reason
    })

    ElMessage.success('帖子已拒绝')

    // 从列表中移除已审核的帖子
    const index = posts.value.findIndex(p => p.id === rejectPostData!.id)
    if (index > -1) {
      posts.value.splice(index, 1)
      total.value--

      // 更新Layout中的待审核数量徽章
      updatePendingCount?.(-1)
    }

    rejectDialogVisible.value = false

    // 如果是在详情对话框中操作，关闭对话框
    if (detailDialogVisible.value) {
      detailDialogVisible.value = false
    }

  } catch (error) {
    console.error('拒绝审核失败:', error)
  } finally {
    rejecting.value = false
    if (rejectPostData && operationLoading.value[rejectPostData.id]) {
      operationLoading.value[rejectPostData.id].rejecting = false
    }
    rejectPostData = null
  }
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  fetchPosts()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchPosts()
}

onMounted(() => {
  fetchPosts()
})
</script>

<style scoped>
.pending-posts {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.pet-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.pet-photo {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  object-fit: cover;
}

.pet-name {
  font-weight: bold;
  margin-bottom: 2px;
}

.pet-details {
  font-size: 12px;
  color: #666;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.post-detail {
  padding: 10px 0;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-section h4 {
  margin-bottom: 10px;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 5px;
}

.pet-detail {
  display: flex;
  gap: 15px;
}

.pet-detail-photo {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  object-fit: cover;
}

.pet-detail-info p {
  margin: 5px 0;
  line-height: 1.5;
}

.action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
  justify-content: flex-start;
}

.action-btn {
  min-width: 60px;
  padding: 4px 8px;
}
</style>
